package com.jxd.project.travel.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jxd.project.absence.service.IEmpService;
import com.jxd.project.travel.common.Result;
import com.jxd.project.travel.dto.TravelApprovalQueryDTO;
import com.jxd.project.travel.dto.TravelQueryDTO;
import com.jxd.project.travel.model.Ticket;
import com.jxd.project.travel.model.Travel;
import com.jxd.project.travel.service.ITicketService;
import com.jxd.project.travel.service.ITravelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName TravelController
 * @Description TODO
 * @Author 邢子剑
 * @Date 2025/9/24 上午9:09
 * @Version 1.0
 */
@RestController
public class TravelController {
    @Autowired
    private ITravelService travelService;
    @Autowired
    private ITicketService ticketService;
    @Autowired
    private IEmpService empService;

    @PostMapping("/travelList")
    public IPage<Travel> getTravelList(@RequestBody TravelQueryDTO queryDTO) {
        Integer page = queryDTO.getPage();
        Integer limit = queryDTO.getLimit();
        String travelId = queryDTO.getTravelId();
        Integer empno = queryDTO.getEmpno();
        String startTime = queryDTO.getStartTime();
        String endTime = queryDTO.getEndTime();
        return travelService.getTravelList(page, limit, travelId, startTime, endTime, empno);
    }

    @RequestMapping("/insertTravel")
    public Map<String, Object> insertTravel(@RequestBody Travel travel) {
        int result = travelService.insertTravel(travel);
        Map<String, Object> response = new HashMap<>();
        response.put("success", result > 0);
        response.put("travelId", travel.getTravelId()); // ⚠️ 这里 travelId 必须是插入后生成的
        return response;
    }

    @RequestMapping("/updateTravel")
    public boolean updateTravel(@RequestBody Travel travel) {
        return travelService.updateTravel(travel);
    }

    @RequestMapping("/deleteTravel")
    public Result deleteTravel(@RequestBody Map<String, List<String>> payload) {
        List<String> travelIds = payload.get("travelIds");
        if (travelIds == null || travelIds.isEmpty()) {
            return Result.error("未选择要删除的差旅单");
        }

        // 1. 检查每个差旅单的审批状态
        List<String> canDeleteIds = new ArrayList<>();
        List<String> cannotDeleteIds = new ArrayList<>();

        for (String travelId : travelIds) {
            // 查询差旅单审批状态（假设approval=0为未提交，>=1为已提交）
            int approval = travelService.getApprovalByTravelId(travelId);
            if (approval == 0) {
                canDeleteIds.add(travelId);
            } else {
                cannotDeleteIds.add(travelId);
            }
        }

        // 2. 处理不可删除的差旅单
        if (!cannotDeleteIds.isEmpty()) {
            return Result.error("以下差旅单已提交，无法删除：" + cannotDeleteIds);
        }

        boolean flagTickets = ticketService.deleteTravelIdInTicket(travelIds);
        boolean flagTravels = travelService.deleteTravel(travelIds);
        if (flagTravels && flagTickets) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @RequestMapping("/getTravelById")
    public Travel getTravelById(String travelId) {
        return travelService.getOne(travelId);
    }

    @RequestMapping("/moneyToChinese")
    public String moneyToChinese(@RequestBody Map<String, Double> request) {
        // 从请求中获取money参数
        Double money = request.get("money");
        return travelService.moneyToChinese(money);
    }

    //获取差旅信息（审批页面）
    @PostMapping("/getTravelListByEmpno")
    public IPage<Travel> getTravelListByEmpno(@RequestBody TravelApprovalQueryDTO queryDTO) {
        int page = queryDTO.getPage();
        int limit = queryDTO.getLimit();
        int empno = queryDTO.getEmpno();
        int[] roleids = queryDTO.getRoleid();
        boolean all = queryDTO.isAll();
        return travelService.getTravelListByEmpno(page, limit, empno, roleids, all);
    }

    //查询该差旅绑定的车票信息
    @RequestMapping("/getTicketsByTravelId")
    public List<Ticket> getTicketsByTravelId(String travelId) {
        return travelService.getTicketByTravelId(travelId);
    }

    //审核通过
    @RequestMapping("/updateApprovalStatus1")
    public boolean updateApprovalStatus1(@RequestBody TravelApprovalQueryDTO dto) {
        return travelService.updateApprovalStatus1(
                dto.getTravelId(),
                dto.getManagerOpinion(),
                dto.getDirectorOpinion()
        );
    }

    //审核不通过
    @RequestMapping("/updateApprovalStatus2")
    public boolean updateApprovalStatus2(@RequestBody TravelApprovalQueryDTO dto) {
        return travelService.updateApprovalStatus2(
                dto.getTravelId(),
                dto.getManagerOpinion(),
                dto.getDirectorOpinion()
        );
    }

    //查询审核状态
    @RequestMapping("/getApprovalByTravelId")
    public int getApprovalByTravelId(String travelId) {
        return travelService.getApprovalByTravelId(travelId);
    }

    @RequestMapping("/getRejectCount")
    public int getRejectCount(int empno) {
        return travelService.getRejectCount(empno);
    }


}
